package com.example.test.controller;

import com.example.test.annotation.FileTypeAnnotation;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.MessagingException;
import org.springframework.web.bind.annotation.*;

import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.jms.Queue;
import java.util.HashMap;
import java.util.Map;

//@Controller //标明这是一个Spring MVC的Controller控制器
@RestController //@Controller+@ResponseBody 类的方法会自动加上@ResponseBody注解
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    @Qualifier("queue")
    private Queue queue;

    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    public String hello(@PathVariable String name) {
        return "Hello World! " + name;
    }

    @PostMapping("/json/test")
    public void jsonTest(ObjectMapper objectMapper) throws JsonProcessingException {
        Map<String,Object> map = new HashMap<>();
        map.put("name","bob");
        map.put("age",20);
        String json = objectMapper.writeValueAsString(map);
        System.out.println(json);
    }

    @PostMapping("/test")
    @FileTypeAnnotation(type = {"png","jpg"})
    //@RequestBody获取json格式的post数据 @RequestParam不能获取json格式的post
    public void test(MultipartFile file) {
          System.out.println(1);
          int a = 10;
          System.out.println(a/0);
    }

    @RequestMapping(value = "/show/{gid}", method = RequestMethod.GET)
    public String show(@PathVariable("gid") int gid) {
        //System.out.println("goodsId : " + gid);
        return "goodsId : " + gid;
    }

    @GetMapping("/info/gid/{gid}/sid/{sid}")
    public String info(@PathVariable("gid") int gid, @PathVariable("sid") int sid) {
        return "goodsId : " + gid+", specsId : "+sid;
    }

    @PostMapping("/queue/test")
    public String sendQueue(@RequestBody String str) throws MessagingException{
        System.out.println(str);
        try {
            jmsMessagingTemplate.convertAndSend(queue, str);
            return "success";
        }catch (MessagingException e){
            System.out.println(e.getMessage());
            return "error";
        }

    }



}
